package com.xiaoyy.app.extend.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyy.app.extend.common.vo.RongHubTokenResVO;
import com.xiaoyy.app.extend.common.vo.RongHubTokenVO;
import com.xiaoyy.app.extend.integration.RongHubIntegration;
import com.xiaoyy.core.common.exception.AppException;
import com.xiaoyy.core.common.utils.CommonSecureUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class RongHubIntegrationImpl implements RongHubIntegration {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${system.config.ronghub.api.url}")
    private String apiUrl;

    public RongHubTokenResVO getToken(RongHubTokenVO rongHubTokenVO){
        String url = apiUrl+"/user/getToken.json";
        Map<String,Object> params = new HashMap<>();
        params.put("userId",rongHubTokenVO.getUserId());
        params.put("name",rongHubTokenVO.getName());
        Map<String,String> header = new HashMap<>();
        header.put("Content-Type","application/x-www-form-urlencoded");
        header.put("App-Key",rongHubTokenVO.getAppKey());
        String nonce = Long.toString((long)((Math.random()+1)*1000000000000000l));
        header.put("Nonce",nonce);
        String timestamp = Long.toString(new Date().getTime());
        header.put("Timestamp",timestamp);
        String signature = null;
        try {
            signature = CommonSecureUtil.shaEncrypt(rongHubTokenVO.getSecret()+nonce+timestamp);
        } catch (Exception e) {
            logger.error("sha1加密失败",e);
            throw new AppException("融云获取token接口sha1加密失败");
        }
        header.put("Signature",signature);
        String resBody = HttpUtil.createPost(url).form(params).headerMap(header,false).execute().body();
        if(StringUtils.isBlank(resBody)){
            throw new AppException("融云获取token接口返回为空");
        }
        RongHubTokenResVO rongHubTokenResVO = null;
        try {
            rongHubTokenResVO =
                    Convert.convert(RongHubTokenResVO.class, JSONObject.parseObject(resBody));
        }catch (Exception e){
            logger.error("融云获取token接口出参解析失败",e);
            throw new AppException("融云获取token接口出参解析失败");
        }
        return rongHubTokenResVO;
    }
}
